package com.yuntsg.ruiijn.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.yuntsg.ruiijn.database.entity.SysQueen;
import com.yuntsg.ruiijn.database.entity.WosBasic;
import com.yuntsg.ruiijn.database.mapper.SysQueenMapper;
import com.yuntsg.ruiijn.database.mapper.WosBasicMapper;
import com.yuntsg.ruiijn.databse_search.entity.FileDetails;
import com.yuntsg.ruiijn.databse_search.entity.FileRecord;
import com.yuntsg.ruiijn.databse_search.mapper.FileDetailsMapper;
import com.yuntsg.ruiijn.databse_search.mapper.FileRecordsMapper;
import com.yuntsg.ruiijn.databse_search.service.FileDetailService;
import com.yuntsg.ruiijn.databse_search.service.FileRecordsService;
import com.yuntsg.ruiijn.paperana.controller.SearchController;
import com.yuntsg.ruiijn.paperana.service.MatchService;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import common.proxy.HttpUtil;
import common.util.*;
import common.vo.Scenario;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@SuppressWarnings("ALL")
public class AsyncService {
    @Value("${upload.path}")
    public String uploadPath;
    @Value("${unit.onTrial}")
    public Integer onTrial;
    @Resource
    SearchController searchController;
    @Resource
    ManualCheckService manualCheckService;
    @Resource
    MatchService matchService;
    @Resource
    private WosBasicMapper wosBasicMapper;
    @Resource
    private FileDetailService fileDetailService;
    @Resource
    private FileRecordsMapper fileRecordsMapper;
    @Resource
    private FileDetailsMapper fileDetailsMapper;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private FileRecordsService fileRecordsService;
    @Autowired
    private SysQueenMapper sysQueenMapper;

    public static String localDateFilePath() {
        String format = DateUtil.format(new Date(), "yyyyMMdd");
        return format + "/";
    }

    public static void main(String[] args) {
        System.out.println(localDateFilePath());
    }


    public Object check_pdf(Integer wosId, Integer uid, Integer checkFlag) throws IOException {


        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
        if (StringUtil.isNotNull(wosBasic)) {
            wosBasic.setAnalysisTime(System.currentTimeMillis());
            wosBasicMapper.updateById(wosBasic);
            log.info("开始一键分析===============================" + wosId);
            try {
                //先判断使用权限
                String cPy = wosBasic.getCPy();
                if (wosBasic.getSoType() == 1) {//如果要分析的是系统文章
                    if (onTrial == 1) {//如果是使用单位
                        int py = Integer.parseInt(cPy);
                        if (py != 2018 && py != 2019) {//判断是否是18 19年的数据
                            return new ResultBean<>(3, "您当前所在单位为试用单位,只能分析2018,2019年数据");
                        }
                    }
                }
//            if (wosBasic.getSoType() == 2) {//如果分析的是本地文献
//                if (wosBasic.getPaySucc() == 0) {
//                    return new ResultBean<>(3, "当前功能需付款后使用");
//                }
//            }


                String fileName = wosBasic.getCTi().replaceAll(" +", "").trim();
                fileName = RegexUtil.filterNAC(fileName);

                if (wosBasic.getSoType() == 1) {
                    if (StringUtil.isEmpty(wosBasic.getFilePath())) {
                        if (StringUtil.isEmpty(wosBasic.getPdfUrl())) {
                            String abase64 = "";
                            String newLink = "";
                            String url = "";
                            if (!StringUtil.isEmpty(wosBasic.getCPm())) {
                                abase64 = XXTEA.encryptToBase64StringNoSafe(wosBasic.getCPm(), "R0HWlCI3ndd1s8S3");
                                url = "https://www.pubtsg.com/api/getpdfurl.do?unitid=1&type=0&query=" + abase64;

                            } else if (wosBasic.getCUt() != null) {
                                //abase64 = XXTEA.encryptToBase64StringNoSafe(wosBasic.getCUt().split(":")[1], "R0HWlCI3ndd1s8S3");
                                abase64 = XXTEA.encryptToBase64StringNoSafe(wosBasic.getCUt().split(":")[1], "R0HWlCI3ndd1s8S3");
                                url = "https://www.pubtsg.com/api/getpdfurl.do?unitid=1&type=1&query=" + abase64;
                            }
//                        System.out.println("PDF_URL___" + url);
                            BasicCookieStore cookieStore = new BasicCookieStore();
                            String html = HttpUtil.postHtmlQuanWen(cookieStore, url, "", "");

                            Map<String, Object> map = new HashMap<String, Object>();
                            map = JSON.parseObject(html, Map.class);
                            if (map.get("pdfurl") != null) {//1094827  //40
                                String pdfUrl = (String) map.get("pdfurl");
//                            System.out.println("要存放的_PDF_URL___" + pdfUrl);
                                wosBasic.setFileType(1);
                                wosBasic.setPdfUrl(pdfUrl);
                            } else {
                                return new ResultBean<>(3, "暂无全文");
                            }
                        }

                        /**
                         * 开始根据 PDF 链接 获取PDF 文件
                         */
                        String getpdfurl = PdfUtil.getpdfurl(wosBasic.getPdfUrl(), 1, 1);
                        System.out.println("获取到的 PDF 下载链接是___ " + getpdfurl);
                        BasicCookieStore basicCookieStore = new BasicCookieStore();
                        String pdfPath = localDateFilePath() + fileName + ".PDF";
                        boolean flag = common.proxy.HttpUtil.DownPdfWithProxy(basicCookieStore, "https://attach.pubtsg.com/" + getpdfurl, "", uploadPath + pdfPath);
                        wosBasic.setFilePath(pdfPath);
                        wosBasicMapper.updateById(wosBasic);
                        System.out.println("wos1文件下载结果___" + flag);
                        if (!flag) {
                            return new ResultBean<>(3, "暂无全文:2");
                        }
                    }
                }
                String cUt = wosBasic.getCUt();
                String cPm = wosBasic.getCPm();
                String cTi = wosBasic.getCTi();
                if (wosBasic.getCTi().contains("___")) {
                    cTi = cTi.split("___")[1];
                }
                String cAu = wosBasic.getCAu();
                String pdfName = wosBasic.getCTi();
                String pdfPath = uploadPath + wosBasic.getFilePath();
                CheckUtil.checkZFL(null == wosBasic.getFilePath(), "解析文件出错,该文章暂无可分析的本地文件,请联系管理员");

                System.out.println("准备上传的PDF文件路径为___" + pdfPath);//

                /**
                 * 如果文件不存在,则清空当前数据,等待系统任务重新执行
                 */
                if (!FileUtil.exist(pdfPath)) {
                    if (wosBasic.getSoType() == 1 && wosBasic.getFileType() == 1) {
                        System.out.println("文件不存在");
                        wosBasic.setFilePath("");
                        wosBasic.setPdfUrl("");
                        wosBasicMapper.updateById(wosBasic);
                        System.out.println("已清空 wos 数据,准备重新下载");
                        return null;
                    }
                }

                if (wosBasic.getSoType() == 1 && wosBasic.getPicCount() == 0) {
                    try {
                        if (wosBasic.getFilePath().toUpperCase().endsWith(".PDF")) {
                            int countPic = PDFCountUtil.getImgSum(uploadPath, wosBasic.getFilePath());
                            wosBasic.setPicCount(countPic);
                            if (countPic == 0) {
                                CheckUtil.checkZFL(true, "解析文件出错,该文件图片数量为 0");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("PDF文件拆图片数量报错");
                    }
                }


                if (!StringUtil.isEmpty(pdfPath) && pdfPath.length() > 5) {
                    FileRecord fileRecord = new FileRecord();
                    if (wosBasic.getFileType() != 4) {//如果不是图片  1WOS_PDF 2 本地PDF 3 WORD 4 图片
                        try {
                            if (null != wosBasic.getSplitType() && wosBasic.getSplitType() == 4) {//如果是国自然数据
                                System.out.println("准备进行国自然数据拆分");
                                String filePath = wosBasic.getFilePath();
                                filePath = uploadPath + filePath;
                                StringBuilder stringBuilder = new StringBuilder();
                                if (wosBasic.getFileType() == 2) {//PDF
                                    stringBuilder = stringBuilder.append(SplitAndExtractText.cutPDF(filePath));
                                } else if (wosBasic.getFileType() == 3) {//DOC 数据
                                    stringBuilder = stringBuilder.append(SplitAndExtractText.readDocFile(filePath));
                                }
                                System.out.println("参数文本长度___" + stringBuilder.length());

                                try {

                                    Integer integer = 0;

                                    integer = manualCheckService.dealSinCheckAsync(0, stringBuilder.toString(), wosBasic.getAuthor(), wosBasic.getCTi(), null, null, uid);

                                    wosBasic.setReFiD(integer);
                                    wosBasic.setSplitAs(0);
                                    wosBasicMapper.updateById(wosBasic);
                                    System.out.println("refid_" + integer);
                                    return new ResultBean<>("解析完成");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.error("提取文字信息失败");
                                }

                            }
                        } catch (Exception e) {
                            System.out.println("拆分国自然数据报错");
                        }


                        File file = FileUtil.file(pdfPath);
                        String md5 = SecureUtil.md5(FileUtil.getInputStream(file));
//                    FileRecord one = fileRecordsService.getOne(Wrappers.<FileRecord>lambdaQuery().eq(FileRecord::getMd5, md5).eq(FileRecord::getUploadId, uid).last("limit 1"));
//                    //如果文件已存在 选择是否删除旧文件 重新计算
//                    if (null != one) {
//                        if (null != reload) {
//                            if (reload == 1) {
//                                fileRecordsService.getMapper().deleteById(one.getId());
//                                return check_pdf(wosId, 0, uid);
//                            }
//                        }012
//                        throw new RRException("文件已存在请勿重复上传！！");
//                    }
                        String path = minioUtil.upload(FileUtil.getInputStream(pdfPath), uid, DateUtil.today(), StrUtil.subAfter(pdfPath, "/", true), Scenario.documentation);
                        fileRecord = new FileRecord().setType(2).setAuthor(cAu).setPmut(cPm).setTitle(cTi).setFilePath(path).setUploadId(uid).setUploadTime(DateUtil.date().getTime()).setMd5(md5);
                        fileRecordsService.saveOrUpdate(fileRecord);
                        //是否拆分 如果是空字段默认拆分
                        Integer split = wosBasic.getSplit();
                        if (split == null) {
                            split = 1;
                        }
                        fileRecordsService.extractFiles(FileUtil.getInputStream(file), fileRecord.getId(), uid, file.getName().toLowerCase().endsWith("pdf") ? 2 : 1, "", split);
                        /**
                         * 如果用户选择了图文拆分,则 TODO 这里确认下拆分出来的文字
                         */
                        if (wosBasic.getSplitType() != null) {
                            if (wosBasic.getSplitType() == 3) {
                                //TODO 先关闭文字查重

                                try {
                                    List<FileDetails> list = new LambdaQueryChainWrapper<>(fileDetailsMapper).select(FileDetails::getId, FileDetails::getTxtContent).eq(FileDetails::getTpye, 1).eq(FileDetails::getRid, fileRecord.getId()).list();
                                    StringBuilder stringBuilder = new StringBuilder();
                                    // todo gcr  老板原来代码意思参文以下的不要了 需要剔除 2023年9月26日08:31:03
                                    T:
                                    for (FileDetails fileDetails : list) {
                                        String paragraphName = fileDetails.getParagraphName();
                                        if (paragraphName != null && paragraphName.equals("references")) { // 参文及参文之后的内容，不再要。
                                            break T;
                                        }
                                        stringBuilder.append(fileDetails.getTxtContent()).append("\n");
                                    }
                                    String string = stringBuilder.toString();
                                    log.info("准备进行文字拆分");
                                    long date = System.currentTimeMillis();
                                    try {
                                        String pmorut = "";
                                        if (StringUtil.isNotNull(cUt)) {
                                            pmorut = cUt;
                                        }
                                        if (StringUtil.isNotNull(cPm)) {
                                            pmorut = pmorut + "," + cPm;
                                        }
                                        if (StringUtil.isNull(wosBasic.getPushFlag())) {
                                            wosBasic.setPushFlag(0);
                                        }
//                                    log.info("wosBasic.getMasterId()+" + wosBasic.getMasterId());
//                                    log.info(" wosBasic.getPushFlag()+" + wosBasic.getPushFlag());
//                                    log.info("wosBasic.getAnnex()+" + wosBasic.getAnnex());
//                                    log.info("wosBasic.getMaster()+" + wosBasic.getMaster());
//                                    log.info("wosBasic.getAuthor()+" + wosBasic.getAuthor());
//                                    log.info("wosBasic.getBelongDate()+" + wosBasic.getBelongDate());
//                                    log.info("wosBasic.getCTi()+" + wosBasic.getCTi());
//                                    log.info("wosId+" + wosId);
//                                    log.info("uid+" + uid);
//                                    String finalPmorut = pmorut;
//                                    SmallTool.printMessError("文字开始");
//                                    // 创建一个固定大小的线程池作为Executor
//                                    ExecutorService executor = Executors.newFixedThreadPool(1);
//                                    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//                                        SmallTool.printMessError("Running an asynchronous task without returning a result.");
//                                        matchService.addZFLComService(wosBasic.getCPy(), wosBasic.getFilePath(), string, wosBasic.getMasterId(),
//                                                wosBasic.getPushFlag(), wosBasic.getAnnex(),
//                                                wosBasic.getMaster(), wosBasic.getAuthor(), wosBasic.getBelongDate(), wosBasic.getCTi(), wosId, uid, wosId + "", 1, finalPmorut, wosBasic.getSelfTxt());
//                                    }, executor);
//                                    // 可以选择等待异步任务完成（非必须）
//                                    future.thenRun(() -> SmallTool.printMessError("Asynchronous text task completed."));
//                                    // 关闭线程池（实际应用中应在程序结束时关闭）
//                                    executor.shutdown();
//                                    System.out.println("执行了后面操作+++");
//                                    try {
//                                        // 非阻塞查询示例：轮询检查任务是否完成
//                                        while (!future.isDone()) {
//                                            System.out.println("文字任务还未完成，稍等...");
//                                            Thread.sleep(60000); // 模拟等待，实际应用中可能不需要这样的等待
//                                        }
//                                        // 获取任务结果
//                                        String result = future.get(5, TimeUnit.SECONDS); // 这里会阻塞，直到结果可用
//                                        System.out.println("文字异步任务返回结果: " + result);
//                                    } catch (InterruptedException | ExecutionException e) {
//                                        e.printStackTrace();
//                                    } catch (TimeoutException e) {
//                                        throw new RuntimeException(e);
//                                    } finally {
//                                        // 关闭线程池，释放资源
//                                        executorService.shutdown();
//                                    }
                                    } catch (Exception e) {
                                        log.error("进入gcr方法提取文字信息失败");
                                    }

                                } catch (Exception e) {
                                    // new RuntimeException("用户选择图文分析出错");
                                    e.printStackTrace();
                                }
//                            }
                            }
                        }
                    } else {//如果是图片
                        fileRecord = new FileRecord().setType(2).setAuthor(cAu).setPmut(cPm).setTitle(cTi).setFilePath(wosBasic.getPdfUrl()).setUploadId(uid).setUploadTime(DateUtil.date().getTime()).setMd5(RandomUtil.randomString(5));
                        fileRecordsService.saveOrUpdate(fileRecord);
                        fileRecordsService.pics(fileRecord.getId(), uid, wosBasic.getFilePath());
                    }

                    wosBasic.setAnalysisFlag(1);
                    Map<Integer, Integer> map = new HashMap<>();
                    map.put(1, fileRecord.getId());
                    wosBasic.setAnalysisMap(JSONObject.toJSONString(map));
                    wosBasic.setRid(fileRecord.getId());
                    wosBasicMapper.updateById(wosBasic);

                    /**
                     * 做记录
                     */
                    SysQueen one = sysQueenMapper.selectById(checkFlag);
                    one.setStatus(1);
                    one.setCheckFlag(0);//添加到显示通知
                    sysQueenMapper.updateById(one);

//            if (uid != null) {
//                Map<Integer, Integer> map = new HashMap<>();
//                String analysisMap = wosBasic.getAnalysisMap();
//                if (StringUtil.isEmpty(analysisMap) || analysisMap.length() <= 2) {
//                    map.put(uid, fileRecord.getId());
//                    wosBasic.setAnalysisMap(JSONObject.toJSONString(map));
//                    wosBasicMapper.updateById(wosBasic);
//                } else {
//                    map = JSONObject.parseObject(analysisMap, Map.class);
//                    map.put(uid, fileRecord.getId());
//                    wosBasic.setAnalysisMap(JSONOUnitController.java:351bject.toJSONString(map));
//                    wosBasicMapper.updateById(wosBasic);
//                }
//            }
                    //全网 与篇内
//                if (checkFlag == null) {
//                    System.out.println("开始进行篇内查重和一键分析");
//                    try {
//                        FileRecord finalFileRecord = fileRecord;
//                        Integer finalUid = uid;
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                try {
//                                    fileDetailService.fetchJsonResultSigle(finalFileRecord, finalUid, wosId);
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        }).start();
//                        System.out.println("论文剖析篇内_全网_成功");
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        wosBasic.setAnalysisFlag(-2);
//                        wosBasicMapper.updateById(wosBasic);
//                        System.out.println("论文剖析篇内_全网_失败");
//                    }
//                }

                    return new ResultBean<>("解析完成");
                }
            } catch (Exception exception) {
                wosBasic.setAnalysisFlag(-2);
                wosBasicMapper.updateById(wosBasic);
                SysQueen one = sysQueenMapper.selectById(checkFlag);
                one.setStatus(-2);
                sysQueenMapper.updateById(one);
                exception.printStackTrace();
            }
        }


        return new ResultBean<>("操作失败,当前文章无法获取全文无法进行分析");
    }


    /**
     * 获取PDF文件
     *
     * @param pdfPath
     * @param uid
     * @param gid
     * @return
     */

}
